//
//  LMJDropdownMenu.m
//
//  Created by JerryLMJ on 15/5/4.
//  Copyright (c) 2015年 LMJ. All rights reserved.
//

#import "LMJDropdownMenu.h"
#import "LMJDropDownMenuCell.h"
#import "CampusParamItemModel.h"
@interface LMJDropdownMenu() <UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

@property (nonatomic, strong) UITableView *optionsList;  // 下拉列表
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) UIButton *coverBtn;


@end



@implementation LMJDropdownMenu
{
    BOOL _isOpened;
}

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initProperties];
        [self initViews];

    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self initProperties];
    [self initViews];
}


#pragma mark - Init
- (void)initProperties{
   
    _animateTime            = 0.3f;

    _isOpened               = NO;
}

- (void)initViews{
    self.layer.masksToBounds = YES;
    
    self.coverBtn = [[UIButton alloc]init];
    [self.coverBtn addTarget:self action:@selector(hideDropDown) forControlEvents:UIControlEventTouchUpInside];

    
    // 下拉列表TableView
    _optionsList = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _optionsList.estimatedRowHeight = 100;
    _optionsList.estimatedSectionHeaderHeight = .0f;
    _optionsList.estimatedSectionFooterHeight = .0f;
    _optionsList.delegate       = self;
    _optionsList.dataSource     = self;
    _optionsList.separatorStyle = UITableViewCellSeparatorStyleNone;
    _optionsList.scrollEnabled  = NO;
    _optionsList.showsVerticalScrollIndicator = NO;
    _optionsList.showsHorizontalScrollIndicator = NO;
    _optionsList.backgroundColor = [UIColor whiteColor];
    
    _line = [[UIView alloc]init];
    _line.backgroundColor = RGBA(230, 230, 230, 1);
    
}


#pragma mark - Action Methods
- (void)reloadOptionsData{
    
    CGFloat listHeight = 0;
    NSUInteger count = [self.dataSource numberOfOptionsInDropdownMenu:self];
    for (int i = 0; i < count; i++) {
        CGFloat cHeight = [self.dataSource dropdownMenu:self heightForOptionAtIndex:i];
        listHeight += cHeight;
    }
    listHeight+=6;
    if (self.optionsListLimitHeight < listHeight) { // 当未设置下拉菜单最小展示高度
        listHeight = self.optionsListLimitHeight;
        _optionsList.scrollEnabled = YES;
    } else {
        _optionsList.scrollEnabled = NO;
    }
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:self.animateTime animations:^{

        UITableView *listView = weakSelf.optionsList;

        listView.cl_height = listHeight;

    }completion:^(BOOL finished) {
       
    }];
    
    [self.optionsList reloadData];
    
    // 判断数据是否有选中
    NSArray *dataArray = [self.dataSource dropdownMenuListSource];
    __block NSInteger index = -1;
    
    [dataArray enumerateObjectsUsingBlock:^(CampusParamItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            index = idx;
            *stop = YES;
        }
    }];
    
    // 刷新下拉列表数据
    [self.optionsList reloadData];
    
    if (index != -1) {
        [self.optionsList scrollToRow:index inSection:0 atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    }else{
        [self.optionsList scrollToRow:0 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
    
}

- (void)showDropDownInView:(UIView *)mainView{
    [mainView addSubview:self];
    
    // 菜单高度计算
    CGFloat listHeight = 0;
    NSUInteger count = [self.dataSource numberOfOptionsInDropdownMenu:self];
    for (int i = 0; i < count; i++) {
        CGFloat cHeight = [self.dataSource dropdownMenu:self heightForOptionAtIndex:i];
        listHeight += cHeight;
    }
    listHeight+=6;
    if (self.optionsListLimitHeight < listHeight) { // 当未设置下拉菜单最小展示高度
        listHeight = self.optionsListLimitHeight;
        _optionsList.scrollEnabled = YES;
    } else {
        _optionsList.scrollEnabled = NO;
    }
    
    _isOpened = YES;
    // 变更menu图层
    
    self.frame = CGRectMake(0,self.anchorPoint.y, kScreenW, kScreenH);
    
    self.backgroundColor = RGBA(0, 0, 0, 0.7);
    
    _coverBtn.frame = self.frame;
    
    _optionsList.frame = CGRectMake(0,0,kScreenW,0);
    
    _line.frame = CGRectMake(0, 0, kScreenW, 0.5);
    
    [self addSubview:_coverBtn];
    
    [self addSubview:_optionsList];
    
    [self addSubview:_line];

//     call delegate
    if ([self.delegate respondsToSelector:@selector(dropdownMenuWillShow:)]) {
        [self.delegate dropdownMenuWillShow:self]; // 将要显示回调代理
    }

  
    
    // 执行展开动画
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:self.animateTime animations:^{

        UITableView *listView = weakSelf.optionsList;

        listView.cl_height = listHeight;

    }completion:^(BOOL finished) {
        if ([self.delegate respondsToSelector:@selector(dropdownMenuDidShow:)]) {
            [self.delegate dropdownMenuDidShow:self]; // 已经显示回调代理
        }
    }];
    
    // 判断数据是否有选中
    NSArray *dataArray = [self.dataSource dropdownMenuListSource];
    __block NSInteger index = -1;
    [dataArray enumerateObjectsUsingBlock:^(CampusParamItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            index = idx;
            *stop = YES;
        }
    }];
    // 刷新下拉列表数据
    [self.optionsList reloadData];
    if (index != -1) {
        [self.optionsList scrollToRow:index inSection:0 atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    }else{
        [self.optionsList scrollToRow:0 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
    
}


- (void)hideDropDown{  // 隐藏下拉列表
    // call delegate
    if ([self.delegate respondsToSelector:@selector(dropdownMenuWillHidden:)]) {
        [self.delegate dropdownMenuWillHidden:self]; // 将要隐藏回调代理
    }

    // 执行关闭动画
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:self.animateTime animations:^{
      
        weakSelf.optionsList.cl_height = 0;
     
    }completion:^(BOOL finished) {
       
        [weakSelf removeFromSuperview];
        
        self->_isOpened = NO;
        
        if ([self.delegate respondsToSelector:@selector(dropdownMenuDidHidden:)]) {
            [self.delegate dropdownMenuDidHidden:self]; // 已经隐藏回调代理
        }
    }];
    
}
- (void)dismissMenu{
    
    self.optionsList.cl_height = 0;
    
    [self removeFromSuperview];
    
    self->_isOpened = NO;
    
    if ([self.delegate respondsToSelector:@selector(dropdownMenuDidHidden:)]) {
        [self.delegate dropdownMenuDidHidden:self]; // 已经隐藏回调代理
    }
}

#pragma mark - Utility Methods
- (CGPoint)getScreenPosition {
    return [self.superview convertPoint:self.frame.origin toView:[self getCurrentKeyWindow]];
}

- (UIWindow *)getCurrentKeyWindow {
    return [UIApplication sharedApplication].keyWindow;
}

#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource numberOfOptionsInDropdownMenu:self];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.dataSource dropdownMenu:self heightForOptionAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger index = indexPath.row;
    
    CampusParamItemModel *itemModel = [self.dataSource dropdownMenu:self itemModelForOptionAtIndex:index];
    LMJDropDownMenuCell *cell = [LMJDropDownMenuCell cellWithTableView:tableView];
    [cell setModel:itemModel];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 6.0f;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 6)];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 

    NSArray *dataArray = [self.dataSource dropdownMenuListSource];
    
    [dataArray enumerateObjectsUsingBlock:^(CampusParamItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == indexPath.item) {
            obj.isSelected = YES;
        }else{
            obj.isSelected = NO;
        }
    }];
    
    if ([self.delegate respondsToSelector:@selector(dropdownMenu:didSelectOptionAtIndex:itemModel:)]) {
        [self.delegate dropdownMenu:self didSelectOptionAtIndex:indexPath.row itemModel:dataArray[indexPath.item]];
    }
    // 执行关闭动画
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:self.animateTime animations:^{
      
        weakSelf.optionsList.cl_height = 0;
     
    }completion:^(BOOL finished) {
       
        [weakSelf removeFromSuperview];
        
        self->_isOpened = NO;
            
    }];
    
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
   if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
       return NO;
   }
   return  YES;
}


#pragma mark - Get Methods
- (BOOL)showsVerticalScrollIndicatorOfOptionsList {
    return _optionsList.showsVerticalScrollIndicator;
}


- (void)setShowsVerticalScrollIndicatorOfOptionsList:(BOOL)showsVerticalScrollIndicatorOfOptionsList {
    _optionsList.showsVerticalScrollIndicator = showsVerticalScrollIndicatorOfOptionsList;
}

@end




